package com.nightpiter.model.reader.xml.sax;

import static com.nightpiter.controller.log.Logger.log;
import static com.nightpiter.controller.log.Logger.logException;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;

import com.nightpiter.model.MetroModel;
import com.nightpiter.model.exceptions.ModelNotAssignedBuilderException;
import com.nightpiter.model.reader.xml.XmlReader;

/**
 * XmlModelReader realization using SAX
 * 
 * @author Hanhe
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 * 
 */
public class SaxReader extends XmlReader {
	/**
	 * public constructor
	 * 
	 * @throws ModelNotAssignedBuilderException
	 */
	public SaxReader(MetroModel model) throws ModelNotAssignedBuilderException {
		super(model);
	}

	/**
	 * parse the inputStream
	 */
	protected void parse(InputStream inputStream) throws IOException {
		try {
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			XMLReader xr = parser.getXMLReader();
			SaxEventsHandler handler = new SaxEventsHandler(this.modelBuilder);

			xr.setContentHandler(handler);
			xr.setErrorHandler(handler);

			InputSource inputSource = new InputSource(inputStream);

			xr.parse(inputSource);

		} catch (FactoryConfigurationError fce) {
			logException(fce);
			log("Parsing failed");
		} catch (ParserConfigurationException pce) {
			logException(pce);
			log("Parsing failed");
		} catch (SAXParseException spe) {
			logException(spe);
			log("Parsing failed");
		} catch (SAXException saxe) {
			logException(saxe);
			log("Parsing failed");
		}

	}

}
